﻿using System;
using System.CommandLine;
using System.IO;

namespace DemoCommandLine
{
    internal class Grep
    {
        public Grep(RootCommand rootCmd)
        {
            var search = new Argument<string>(name: "search");
            var filePath = new Argument<string>(name: "file");
            filePath.SetDefaultValue("");
            var cast = new Option<bool>("--cast");
            cast.AddAlias("-c");
            cast.SetDefaultValue(false);
            var subCom = new Command("grep", "print file content") { cast, search, filePath };
            subCom.SetHandler((filePathValue, searchValue, castValue) =>
            {
                if (File.Exists(filePathValue))
                {
                    Console.WriteLine(File.ReadAllText(filePathValue));
                    return;
                }
                while (true)
                {
                    if (Console.Read() == -1)
                    {
                        break;
                    }
                    if (castValue)
                    {
                        string data = Console.ReadLine();
                        if (data.ToLower().Contains(searchValue.ToLower()) && data.Length > 0)
                        {
                            Console.WriteLine(data);
                        }
                    }
                    else
                    {
                        string data = Console.ReadLine();
                        if (data.Contains(searchValue) && data.Length > 0)
                        {
                            Console.WriteLine(data);
                        }
                    }
                }
            }, filePath, search, cast);
            rootCmd.Add(subCom);
        }
    }
}
